//logs.js
import store from "../../utils/factory";
import {
  getDetail,
  getShopCarList,
  shopCarAdd,
  getComment
} from "../../utils/config";
//获取应用实例
const app = getApp();
let that = null;

Page({
  data: {
    logs: [],
    count: 0,
    isActive: 1,
    detailObj: {},
    list: []
  },
  onLoad: function (e) {
    that = this;
    this.getDetail(e.id);
    that.getComment(e.id)
  },
  change(e) {
    const isActive = e.currentTarget.dataset.active;
    console.log(isActive)
    that.setData({
      isActive: isActive
    })
  },
  onShow() {
    if (store.get("userInfo")) {
      this.getTotal();
    }
  },
  getTotal() {
    getShopCarList().then(res => {
      let req = res.data;
      this.setData({
        count: req.quantity
      });
    });
  },
  getComment(id) {
    getComment({
      id: id,
      page: 1,
      limit: 99
    }).then(res => {
      if (res.rows.length > 0) {
        let req = res.rows;
        that.setData({
          list: req
        })
      }
    })
  },
  goShopCarList() {
    if (store.get("pageSource")) {
      store.remove("pageSource");
    }
    wx.switchTab({
      url: "../shopCar/shopCar"
    });
  },
  addShopCar: function () {
    if (!store.get("userInfo")) {
      wx.navigateTo({
        url: "../autoLogin/autoLogin" // 页面 B
      });
      return false;
    }
    if (!this.data.detailObj) {
      wx.showToast({
        title: "该商品不存在",
        icon: "none"
      });
      return false;
    }
    if (this.data.detailObj.saleOut) {
      wx.showToast({
        title: "该商品已经售罄",
        icon: "none"
      });
      return false;
    }
    shopCarAdd({
      category: this.data.detailObj.id,
      quantity: 1
    }).then(res => {
      wx.showToast({
        title: "添加购物车成功",
        icon: "none",
        duration: 1000
      });
      that.setData({
        count: parseInt(that.data.count) + 1
      });
    });
  },
  getDetail(id) {
    wx.showLoading({
      title: "加载商品中..."
    });
    getDetail({
      id: id
    }).then(res => {
      console.log(res.data);
      this.setData({
        detailObj: res.data
      });
      wx.hideLoading();
    });
  }
});